import os
import pyttsx3
import time
import _thread

engine = pyttsx3.init('sapi5')
# 设置发音速率，默认值为200
engine.setProperty('rate', 120)

speak_lang = 'zh'

SPEAK_THREAD_STOPPED = 'stopped'
SPEAK_THREAD_RUNNING = 'running'
SPEAK_THREAD_CANCLE = 'cancle'
SPEAK_THREAD_EXIT = 'exit'

def execute_unix(inputcommand):
   p = subprocess.Popen(inputcommand, stdout=subprocess.PIPE, shell=True)
   (output, err) = p.communicate()
   return output

def espeakSay(wordsStr):
	# tts using espeak
	# because windows 7 do not use utf-8 string , espeak must use utf-8, so we use python to save string to a file then use espeak to read from file
	msgfile = open(r"c:\AICHAIN\myAI\test\msg.txt", 'w', encoding='utf-8')
	msgfile.write(wordsStr)
	msgfile.close()

	c = 'espeak -vzhy -s150 -g2 -a200 -f c:\\AICHAIN\\myAI\\test\\msg.txt'
	ret = execute_unix(c)
	print (ret)

def sapi5Say(wordsStr):
	global engine
	engine.say(wordsStr)
	engine.runAndWait()

def robotSay(wordsStr):
	global speak_lang

	if speak_lang == 'zh' :
		sapi5Say(wordsStr)
	elif speak_lang == 'zh-yue':
		espeakSay(wordsStr)
	else :
		sapi5Say(wordsStr)

def getSpeakThreadMode():
	speaktrhead_mode = SPEAK_THREAD_STOPPED
	while True:
		with open(r"c:\AICHAIN\myAI\test\speakctrl.txt", 'r', encoding='utf-8') as f:
			speaktrhead_mode = f.readline()
			f.close()
			break
		time.sleep(1)
		
	return speaktrhead_mode

def setSpeakThreadMode(mode):
	while True:
		with open(r"c:\AICHAIN\myAI\test\speakctrl.txt", 'w', encoding='utf-8') as f:
			f.write(mode)
			f.close()
			break
		time.sleep(1)

def speakCancelCMD_Thread( threadName, delay):
	global engine
	
	while True:
		if getSpeakThreadMode() == SPEAK_THREAD_CANCLE :
			print('get cancel speak CMD ...')
			engine.stop()

		if getSpeakThreadMode() == SPEAK_THREAD_STOPPED :
			break
		else :
			time.sleep(3)
	
	print('wait cancel speak CMD thread exit ...')

if __name__=='__main__':
	setSpeakThreadMode(SPEAK_THREAD_STOPPED)

	print('speak in background started.')

	while True:
		speaktrhead_mode = getSpeakThreadMode()
		if speaktrhead_mode == SPEAK_THREAD_RUNNING :
			print('start speak in background...')

			with open(r"c:\AICHAIN\myAI\test\baike.txt", 'r', encoding='utf-8') as f1:
				_thread.start_new_thread( speakCancelCMD_Thread, (0, 0) )

				line = f1.readline()
				while line and getSpeakThreadMode() == SPEAK_THREAD_RUNNING :
					robotSay(line)

					if getSpeakThreadMode() == SPEAK_THREAD_CANCLE :
						break

					line = f1.readline()
				f1.close()

			setSpeakThreadMode(SPEAK_THREAD_STOPPED)
			print('background speak finished.')

		elif speaktrhead_mode == SPEAK_THREAD_EXIT :
			break
		else :
			time.sleep(3)
	
	print('speak background exit...')
